package org.funtester.performance.books.chapter02.section3;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 超时锁示例
 */
public class TimeoutLockDemo {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock = new ReentrantLock();// 创建一个可重入锁
        Thread lockTestThread = new Thread(() -> {// 创建一个线程
            boolean b = lock.tryLock();// 第一次尝试获取锁
            System.out.println(System.currentTimeMillis() + "  第一次获取锁的结果：" + b + "  " + Thread.currentThread().getName());// 打印日志
            try {
                boolean b1 = lock.tryLock(3, TimeUnit.SECONDS);
                System.out.println(System.currentTimeMillis() + "  第二次获取锁的结果：" + b1 + "  " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                System.out.println(System.currentTimeMillis() + "  第二次获取锁中断了  " + Thread.currentThread().getName());

            }
        });
        lock.lock();// 获取锁
        lockTestThread.start();// 启动异步线程
        Thread.sleep(100);// 睡眠100毫秒
        lock.unlock();// 释放锁
    }

}
